#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Debug dataset overview issues
"""

import sys
from pathlib import Path

# Add project root to Python path
project_root = Path(__file__).parent.absolute()
sys.path.insert(0, str(project_root))

def debug_dataset_overview():
    """Debug the dataset overview query that's failing"""
    try:
        from backend.config.database import get_db_session
        from backend.entities.load_data_new import LoadData
        from sqlalchemy import func
        
        print("🔍 正在调试数据集概览查询...")
        
        db = get_db_session()
        try:
            # Try the exact query that's failing
            print("📊 尝试负荷数据统计查询...")
            load_stats = db.query(
                func.count(LoadData.id).label('total_records'),
                func.min(LoadData.dt).label('start_date'),
                func.max(LoadData.dt).label('end_date'),
                func.avg(LoadData.load_val).label('avg_load'),
                func.max(LoadData.load_val).label('max_load'),
                func.min(LoadData.load_val).label('min_load')
            ).first()
            
            print("✅ 负荷数据查询成功!")
            print(f"  - 总记录数: {load_stats.total_records}")
            print(f"  - 开始日期: {load_stats.start_date}")
            print(f"  - 结束日期: {load_stats.end_date}")
            
        except Exception as e:
            print(f"❌ 负荷数据查询失败: {e}")
            print("🔍 尝试更简单的查询...")
            try:
                count = db.query(LoadData).count()
                print(f"✅ 简单计数成功: {count} 条记录")
            except Exception as e2:
                print(f"❌ 简单计数也失败: {e2}")
                
        # Try weather data query
        try:
            from backend.entities.weather_daily import WeatherDaily
            print("\n🌤️  尝试气象数据查询...")
            weather_count = db.query(WeatherDaily).count()
            print(f"✅ 气象数据计数成功: {weather_count} 条记录")
        except Exception as e:
            print(f"❌ 气象数据查询失败: {e}")
            
        db.close()
        
    except Exception as e:
        print(f"❌ 调试失败: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    debug_dataset_overview()